package org.fing.edu.uy.esbadp.mechanism.monitor;

import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.management.MBeanServer;
import javax.management.ObjectName;

import org.apache.commons.lang.exception.ExceptionUtils;
import org.fing.edu.uy.esbadp.core.entity.DMRegisteredService;
import org.fing.edu.uy.esbadp.core.interfaces.IMechanismMonitor;
import org.jboss.mx.util.MBeanServerLocator;



public class MechanismMonitorServiceFails implements IMechanismMonitor {

	private static java.util.logging.Logger logger = Logger.getLogger(MechanismMonitorServiceFails.class.getSimpleName());
	private final static String failedCount = " messages failed count";
	private final static String listenerXML = "ListenerXMLAsHtml";
	private final static String REG_PROXYACTION = ".*\\s+action=\"(.*)\"\\s+class=\"org.jboss.soa.esb.actions.soap.proxy.SOAPProxy\"\\s+.*wsdl=\"(.*)\\?wsdl.*";
	
		
	@Override
	public Object getMonitorValue(DMRegisteredService registeredService) {
		int actionfailedCount = 0;
		try{
			/*get service metadata*/
			MBeanServer mbeanServer = MBeanServerLocator.locateJBoss();
			String serviceObjectString = makeServiceObjectString(registeredService.getVirtualServiceName(), registeredService.getVirtualServiceCategory(), registeredService.getEsbProyectName());
			ObjectName serviceObjectName = new ObjectName(serviceObjectString);
			String listener = (String) mbeanServer.getAttribute(serviceObjectName, listenerXML);
			String proxyActionName = getProxyActionName(listener, registeredService);
			
			/*get counter data*/	
			String counterObjectString = makeServiceCounterObjectString(registeredService.getVirtualServiceName(), registeredService.getVirtualServiceCategory(), registeredService.getEsbProyectName());
			ObjectName counterObjectName = new ObjectName(counterObjectString);				
			actionfailedCount = (Integer) mbeanServer.getAttribute(counterObjectName, proxyActionName + failedCount);	
		}catch (Exception ex) {
			logger.log(Level.SEVERE, "Exception in MechanismMonitorServiceFails when execute getMonitorValue function. \n StackTarce => [ {0} ]",ExceptionUtils.getStackTrace(ex));
		}	
		return actionfailedCount;
	}

	
	private String makeServiceObjectString(String virtualServiceName, String virtualServiceCategory, String proyectName){	
		String domain = "jboss.esb:";
		String deployment = "deployment=" + proyectName; 	
		String serviceName = "service-name=" + virtualServiceName;
		String serviceCategory = "service-category=" + virtualServiceCategory;
		String objectString = domain + deployment + "," + serviceCategory +","+ serviceName;
		return objectString;	
	}
	
	private String makeServiceCounterObjectString(String virtualServiceName, String virtualServiceCategory, String proyectName){
		String domain = "jboss.esb:";
		String counterCategory = "category=MessageCounter";
		String deployment = "deployment=" + proyectName; 	
		String serviceName = "service-name=" + virtualServiceName;
		String serviceCategory = "service-category=" + virtualServiceCategory;
		String objectString = domain + counterCategory + "," + deployment + "," + serviceCategory +","+ serviceName;
		return objectString;
	}
	
	private String getProxyActionName(String listenerHTML, DMRegisteredService virtualService) throws Exception{
		String res = "";
		Pattern patron = Pattern.compile(REG_PROXYACTION);
		Matcher matcher = patron.matcher(listenerHTML);
		if (matcher.find()) {
			String actionName = matcher.group(1);
			String endPoint = matcher.group(2);
			if (endPoint.equalsIgnoreCase(virtualService.getEndPointURL())){
				res = actionName;
			}else{
				logger.log(Level.WARNING, "The virtual service endpoints registered with the listener do not match. ({0} not match {1})", new Object[]{virtualService.getEndPointURL(), endPoint});
			}
		}
		if (res.length() == 0){
			throw new Exception("Exception in getProxActionName, proxy endpoint not found");
		}
		return  res;
	} 
	
}
